<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>
          <el-button
            @click="openDrawer('add')"
            icon="el-icon-plus"
            size="small"
            type="primary"
            round
          >
            添加面经
          </el-button>
        </div>
      </template>
      <!-- 卡片内容 -->
      <el-table stripe :data="list" style="width: 100%">
        <el-table-column prop="stem" label="标题" width="400">
        </el-table-column>
        <el-table-column prop="creator" label="作者"> </el-table-column>
        <el-table-column prop="likeCount" label="点赞"> </el-table-column>
        <el-table-column prop="views" label="浏览"> </el-table-column>
        <el-table-column
          prop="createdAt"
          label="更新日期"
          width="180"
          sortable
          :sort-by="(row) => new Date(row.createdAt).getTime()"
        >
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <div class="actions">
              <i class="el-icon-view" @click="openDrawer('view', row.id)"></i>
              <i
                class="el-icon-edit-outline"
                @click="openDrawer('edit', row.id)"
              ></i>
              <i class="el-icon-delete" @click="del(row.id)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 25, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 抽屉 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawer"
      :before-close="handleClose"
      size="50%"
    >
      <!-- 添加，修改操作，操作内容为表单 -->
      <!-- lebal-width 标题和输入框一行显示 -->
      <el-form v-if="drawerType !== 'view'"
      label-width="80px" :model="form" :rules="rules" ref="form">
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem" placeholder="输入面经标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quill-editor
            v-model="form.content"
            @blur="$refs.form.validateField('content')"
          ></quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
      <!-- 预览操作不是表单，可以是div -->
      <div v-else class="article-preview">
        <h5>{{ form.stem }}</h5>
        <div v-html="form.content"></div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";
import {
  ArticleListAPI,
  addArticleAPI,
  removeArticleAPI,
  showArticleAPI,
  updateArticleAPI,
} from "@/api/article";
export default {
  name: "article-page",
  components: {
    quillEditor,
  },
  data() {
    return {
      drawer: false, // 控制抽屉的开关
      current: 1, // 默认获取第一页
      pageSize: 10, // 每页最大数据
      list: [], // 存储数据
      total: 0, // 数据总数
      drawerType: null, // 抽屉类型
      form: {
        stem: "",
        content: "",
      },
      rules: {
        stem: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
      },
    };
  },
  async created() {
    this.initDate();
  },
  methods: {
    async initDate() {
      const {
        data: { rows, total },
      } = await ArticleListAPI({
        current: this.current,
        pageSize: this.pageSize,
      });
      this.list = rows;
      this.total = total;
    },
    // 删除数据
    async del(id) {
      try {
        await removeArticleAPI(id);
        this.$message.success("删除成功");
        this.initDate();
      } catch (e) {
        if (e.response) {
          this.$message.error(e.response.data.message);
        } else {
          this.$message.error("删除失败");
        }
      }
    },
    // 选择 条数/页 后触发
    handleSizeChange(val) {
      // val 变化后的 条数/页
      this.pageSize = val;
      this.initDate();
    },
    // 页码变化后触发
    handleCurrentChange(val) {
      // val 当前页码
      this.current = val;
      this.initDate();
    },
    // 打开抽屉
    async openDrawer(type, id) {
      this.drawerType = type;
      if (type !== "add") {
        const { data } = await showArticleAPI({ id });
        this.form.content = data.content;
        this.form.stem = data.stem;
        this.form.id = data.id;
      }
      this.drawer = true;
    },
    // 关闭抽屉之前执行
    handleClose() {
      this.$refs.form?.resetFields(); // 对象?.方法()  ES6可选链语法。前不是false调用后面方法
      this.form = {
        stem: "",
        content: "",
      }; // 删除对象的属性 【有问题】
      this.drawer = false;
    },
    onSubmit() {
      // 表单.validate(valid=>{valid=true验证通过，valid=false验证不通过})
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 判断是添加还是修改操作
          const msg = this.drawerType === "add" ? `添加` : `修改`;
          try {
            if (this.drawerType === "add") {
              await addArticleAPI(this.form);
            } else {
              await updateArticleAPI(this.form);
            }
            this.handleClose(); // 关闭抽屉（清空表单）
            this.initDate(); // 重新渲染页面
            this.$message.success(msg + "成功"); // 提示一下
          } catch (e) {
            if (e.response) {
              this.$message.error(e.response.data.message);
            } else {
              this.$message.error(msg + "失败");
            }
          }
        }
      });
    },
  },
  computed: {
    drawerTitle() {
      if (this.drawerType === "add") {
        return "添加";
      } else if (this.drawerType === "edit") {
        return "编辑";
      } else {
        return "预览";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
